<template>
  <div class="wrapper capa-card">
    <div class="form-container">
      <el-alert
        v-if="statusData.status === '2'"
        :title="statusData.opinion"
        type="error"
      >
      </el-alert>
      <div class="rule_title">
        <span class="title-l"> <i class="icon_left"></i>投诉处理与报告 </span>
        <!-- <el-link @click="handleClickClose" class="icon-right" icon="el-icon-refresh-left" type="primary">
          返回上一页
        </el-link> -->
      </div>
      <el-form
        label-position="right"
        :model="ruleForm"
        class="comp-form"
        label-width="150px"
        :inline="true"
        :rules="rules"
        ref="ruleForm"
        :disabled="disable"
      >
        <el-form-item label="运单号" prop="waybill_no">
          <div @click="handleBindWaybill">
            <el-input v-model="ruleForm.waybill_no"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="客户名称" prop="customer_id">
          <!-- <el-input v-model="ruleForm.customer_id"></el-input> -->
          <el-select
            filterable
            remote
            reserve-keyword
            :remote-method="searchCustomerList"
            v-model="ruleForm.customer_id"
            @change="handleChangeCustomer"
          >
            <el-option
              v-for="item in clientList"
              :key="item.id"
              :label="item.name"
              :value="item.id + ''"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户账号" prop="customer_account">
          <!-- <el-input v-model="ruleForm.customer_account"></el-input> -->

          <el-select v-model="ruleForm.customer_account">
            <el-option
              v-for="item in accountData"
              :key="item.id"
              :label="item.name"
              :value="item.id + ''"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户所属组织" prop="customer_area_id">
          <el-select v-model="ruleForm.customer_area_id">
            <el-option
              v-for="item in reqWebsiteData"
              :key="item.id"
              :label="item.name"
              :value="item.id + ''"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="投诉来源" prop="complaint_source">
          <el-input v-model="ruleForm.complaint_source"></el-input>
        </el-form-item>
        <el-form-item label="事故/投诉发生日期" prop="occur_time">
          <el-date-picker
            v-model="ruleForm.occur_time"
            type="datetime"
            placeholder="选择日期时间"
            value-format="timestamp"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发生地区" prop="area">
          <!-- <el-input v-model="ruleForm.occur_area_id"></el-input> -->
          <el-cascader
            :props="cascaderProps"
            filterable
            clearable
            :options="areaData"
            v-model="ruleForm.area"
            @change="handleAddrChange"
            placeholder="请选择省市区"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="发生部门" prop="occur_department_id">
          <el-cascader
            ref="cascader"
            :options="branchData"
            :show-all-levels="false"
            v-model="ruleForm.occur_department_id"
            :props="{
              emitPath: false,
              checkStrictly: true,
              label: 'branch_name',
              value: 'id',
              children: 'next_level_data',
            }"
            clearable
          >
          </el-cascader>
        </el-form-item>
        <el-divider
          style="margin-top: 10px"
          class="capa-divider"
          content-position="left"
        ></el-divider>
        <el-form-item label="问题描述" prop="problem_desc">
          <el-input v-model="ruleForm.problem_desc"></el-input>
        </el-form-item>
        <el-form-item label="货物名称" prop="goods_category">
          <el-input v-model="ruleForm.goods_category"></el-input>
        </el-form-item>
        <el-form-item label="是否危险品" prop="is_dangerous_goods">
          <el-radio-group
            @input="handleChangeDanger"
            v-model="ruleForm.is_dangerous_goods"
          >
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.is_dangerous_goods === '1'"
          label="危险品 UN 号"
          prop="dangerous_goods_un_number"
        >
          <el-input v-model="ruleForm.dangerous_goods_un_number"></el-input>
        </el-form-item>
        <el-form-item label="包装类型" prop="package_type">
          <el-input v-model="ruleForm.package_type"></el-input>
        </el-form-item>
        <el-form-item label="货物件数" prop="goods_number">
          <el-input v-model="ruleForm.goods_number"></el-input>
        </el-form-item>
        <el-form-item label="温层要求" prop="temperature">
          <el-input v-model="ruleForm.temperature"></el-input>
        </el-form-item>
        <el-form-item label="货物价值" prop="goods_value">
          <el-input v-model="ruleForm.goods_value"></el-input>
        </el-form-item>
        <el-form-item
          label="是否采取紧急措施"
          prop="is_take_emergency_measures"
        >
          <el-radio-group v-model="ruleForm.is_take_emergency_measures">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="
            ruleForm.is_take_emergency_measures == '1'
              ? '采取紧急措施内容'
              : '没有采取的原因'
          "
          prop="take_emergency_measures_content"
        >
          <el-input
            v-model="ruleForm.take_emergency_measures_content"
          ></el-input>
        </el-form-item>
        <el-form-item label="报告人" prop="report_user_id">
          <!-- <el-input v-model="ruleForm.report_user_id"></el-input> -->
          <el-select v-model="ruleForm.report_user_id" filterable clearable>
            <el-option
              v-for="handler in staffData"
              :key="handler.id"
              :label="handler.name"
              :value="handler.id + ''"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="operation-footer" v-if="mode !== 'detail'">
      <div class="footer-wrap">
        <el-button size="small" @click="handleClickClose">关闭</el-button>
        <el-button size="small" type="primary" @click="handleClickSubmit('0')"
          >保存草稿</el-button
        >
        <el-button size="small" type="primary" @click="handleClickSubmit('1')"
          >提交</el-button
        >
      </div>
    </div>
    <WaybillCheck
      :checkedId="ruleForm.waybill_id"
      v-if="waybillDialogVisible"
      :visible="waybillDialogVisible"
      @close="waybillDialogVisible = false"
      @finish="checkWaybillOk"
    ></WaybillCheck>
  </div>
</template>

<script>
import WaybillCheck from "./waybillCheck.vue";
import { customerPeople } from "@/api/information";
import { reqWebsiteList } from "@/api/customer";
import { organizationBox } from "@/api/organization";
import { regionList } from "@/page/material/common/common";

import { CapaInitiated, AdminListByCustomer, CapaUpdate } from "@/api/qms";
import { timestamp10 } from "@/utils/mUtils";
import { AdminBox } from "@/api/customer";

export default {
  name: "complaint",
  components: { WaybillCheck },
  props: ["detailData", "mode", "statusData"],
  data() {
    return {
      ruleForm: {
        waybill_id: "",
        waybill_no: "",
        customer_id: "",
        customer_area_id: "",
        customer_account: "",
        complaint_source: "",
        occur_time: Date.now(),
        occur_area_id: "",
        occur_department_id: "",
        problem_desc: "",
        goods_category: "",
        is_dangerous_goods: "0",
        dangerous_goods_un_number: "",
        package_type: "",
        goods_number: "",
        temperature: "",
        goods_value: "",
        is_take_emergency_measures: "1",
        take_emergency_measures_content: "",
        area: [],
        report_user_id: "",
      },
      rules: {},
      waybillDialogVisible: false,
      clientList: [],
      reqWebsiteData: [],
      branchData: [],
      accountData: [],

      cascaderProps: {
        // multiple: true,
        emitPath: true,
        value: "id",
        label: "name",
        children: "next_level_data",
      },
      areaData: [],
      staffData: [],
    };
  },
  computed: {
    disable() {
      return this.mode === "detail";
    },
  },
  watch: {
    detailData: {
      handler(newValue, oldValue) {
        if (this.detailData) {
          this.getDetail();
        }
      },
      deep: true,
    },
  },
  mounted() {
    reqWebsiteList({
      branch_type: "3",
    }).then((res) => {
      if (res.code === 10000) {
        this.reqWebsiteData = res.data;
      }
    });
    organizationBox({ not_show_first_branch: 1 }).then((res) => {
      this.branchData = res.data;
    });
    regionList().then((res) => {
      const data = res.data || [];

      this.areaData = data;
    });
    AdminBox({
      user_type: "0",
    }).then((res) => {
      this.staffData = res.data;
    });
    if (this.mode === "add") {
      const { user_id } = this.$store.state.user || {};
      this.ruleForm.report_user_id = user_id + "";
    }
  },
  methods: {
    getDetail() {
      const data = JSON.parse(JSON.stringify(this.detailData));
      // data.create_time = data.create_time * 1000 || '';
      // data.close_capa_time = data.close_capa_time * 1000 || '';
      // data.drafting_time = data.drafting_time * 1000 || '';

      // data.occur_duty_department_time = data.occur_duty_department_time * 1000 || '';
      // data.duty_area_leader_id = data.duty_area_leader_id === '0' ? '' : data.duty_area_leader_id;
      // data.quality_control_leader_id = data.quality_control_leader_id === '0' ? '' : data.quality_control_leader_id;

      data.occur_time = data.occur_time * 1000 || "";
      data.occur_area_id =
        data.occur_area_id === "0" ? "" : data.occur_area_id * 1;
      data.occur_department_id =
        data.occur_department_id === "0" ? "" : data.occur_department_id * 1;

      data.customer_id = data.customer_id === "0" ? "" : data.customer_id;
      data.customer_account =
        data.customer_account === "0" ? "" : data.customer_account;
      data.customer_area_id =
        data.customer_area_id === "0" ? "" : data.customer_area_id;

      data.report_user_id =
        data.report_user_id === "0" ? "" : data.report_user_id;

      if (Number(data.occur_province_id)) {
        data.area = [
          data.occur_province_id * 1,
          data.occur_city_id * 1,
          data.occur_district_id * 1,
        ];
      }
      this.ruleForm = data;
      this.searchCustomerid();
      this.getAccountData();
      // console.log(this.ruleForm);
    },
    handleChangeDanger() {
      this.ruleForm.dangerous_goods_un_number = "";
    },
    handleAddrChange(val) {
      if (val) {
        this.ruleForm.occur_province_id = val[0] + "";
        this.ruleForm.occur_city_id = val[1] + "";
        this.ruleForm.occur_district_id = val[2] + "";
      }
    },
    handleClickClose() {
      this.$router.go(-1);
    },
    handleBindWaybill() {
      this.waybillDialogVisible = true;
    },
    async checkWaybillOk(data) {
      Object.assign(this.ruleForm, data);
      // console.log(this.ruleForm,'rrrrrrrrrr')
      this.searchCustomerid(this.ruleForm.customer_id);
      this.getAccountData();
    },

    getAccountData() {
      if (!this.ruleForm.customer_id) return;
      AdminListByCustomer({
        customer_id: this.ruleForm.customer_id,
      }).then((res) => {
        this.accountData = res.data || [];
        if (this.accountData.length === 1) {
          this.ruleForm.customer_account = this.accountData[0].id + "";
        }
      });
    },
    handleChangeCustomer() {
      (this.ruleForm.customer_account = ""),
        // AdminListByCustomer({
        //     customer_id: this.ruleForm.customer_id
        // }).then(res => {
        //     this.accountData = res.data || [];
        //     if (this.accountData.length === 1) {
        //         this.ruleForm.customer_account = this.accountData[0].id +'';
        //     }
        // });
        this.getAccountData();
    },
    handleClickSubmit(is_initiated) {
      const _ruleForm = {
        ...this.ruleForm,
        occur_time: timestamp10(this.ruleForm.occur_time),
        occur_area_id: this.ruleForm.occur_area_id + "",
        occur_department_id: this.ruleForm.occur_department_id + "",
        is_initiated: is_initiated,
      };
      const FN = this.mode === "add" ? CapaInitiated : CapaUpdate;
      FN(_ruleForm).then((res) => {
        // console.log(res);
        if (res.code === 10000) {
          if (is_initiated === "0") {
            this.$message({
              message: "保存草稿成功",
              type: "success",
            });
            let text = this.$router.resolve({
              name: "capaEdit",
              query: {
                id: res.data.id,
                mode: "edit",
              },
            });
            location.replace(text.href);
          } else {
            this.$message({
              message: "提交成功",
              type: "success",
            });
            setTimeout(() => {
              this.$router.push({
                name: "capaList",
              });
            }, 200);
          }
        }
      });
    },
    searchCustomerList(query) {
      //获取客户
      if (query !== "") {
        setTimeout(async () => {
          let result = await customerPeople({
            name: query, // 名称
            id: "",
            is_send: "1",
            is_receive: "",
          });
          if (result.data.length > 0) {
            this.clientList = result.data;
          } else {
            this.clientList = [];
          }
        }, 200);
      } else {
        this.clientList = [];
      }
    },
    // 所属客户
    searchCustomerid() {
      const id = this.ruleForm.customer_id;
      customerPeople({
        name: "", // 名称
        id: id,
        is_send: "1",
        is_receive: "",
      }).then((result) => {
        if (result.data.length > 0) {
          this.clientList = result.data;
        } else {
          this.clientList = [];
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  .rule_title {
    // background: red;
    display: flex;
    align-items: center;
    padding-bottom: 18px;
    padding-top: 8px;
    font-size: 14px;
    font-weight: bold;
    justify-content: space-between;

    .title-l {
      display: flex;
      align-items: center;
    }

    .icon_left {
      display: inline-block;
      width: 6px;
      height: 16px;
      background: #f1a357;
      margin-right: 6px;
    }

    .icon-right {
    }
  }

  .range_tab {
    width: 100%;
    height: 30px;
    background: #f2f3f5;
    font-weight: bold;
    line-height: 30px;
    padding-left: 12px;
    margin-bottom: 16px;
    color: #6d6e72;
    font-size: 14px;
  }

  .comp-form {
    .el-input {
      width: 200px;
    }

    .el-select,
    .el-cascader,
    .el-radio-group {
      width: 200px;
    }

    .el-textarea {
      width: 400px;
    }

    /deep/ .el-form-item {
      margin-right: 30px !important;
    }
  }

  // .operation-footer {
  //     position: fixed;
  //     width: 100%;
  //     bottom: 0;
  //     background: white;
  //     box-sizing: border-box;
  //     padding: 15px 0;
  //     box-shadow: 0px -10px 20px -10px rgba(0, 0, 0, 0.07);
  //     z-index: 100;

  //     .footer-wrap {
  //         width: 86.3%;
  //         text-align: center;
  //     }
  // }
}
</style>